package com.emm.yixun.openapi.hander.base;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.openapi.dto.base.BaseRequestDTO;
import com.emm.yixun.openapi.dto.base.BaseResponseDTO;
import com.emm.yixun.openapi.dto.base.DefaultRes;
import com.emm.yixun.openapi.dto.base.OvalUtil;
import com.emm.yixun.openapi.dto.exception.OvalUNCheckedException;
import com.emm.yixun.openapi.dto.exception.XFUNCheckedException;

public abstract class CommonAbstractHander {
	private static Log logger = LogFactory.getLog(CommonAbstractHander.class);

	public BaseResponseDTO hander(BaseRequestDTO reqDto) {
		logger.info("API业务处理开始:=>" + JSON.toJSON(reqDto));
		BaseResponseDTO resDto = null;
		try {
			// 验签
			// 参数有效性验证
			OvalUtil.validate(reqDto.getParams());
			// 业务处理
			resDto = doBusiness(reqDto);
		} catch (OvalUNCheckedException e) {
			resDto = new BaseResponseDTO<DefaultRes>();
			DefaultRes defaultRes = BaseResponseDTO.getDefaultResDto();
			defaultRes.setErrorMsg(e.getMessage());
			defaultRes.setErrorCode(e.getCode());
			resDto.setResData(defaultRes);
			logger.error("CommonAbstractHander OvalUNCheckedException error: ", e);
		} catch (XFUNCheckedException e) {
			DefaultRes defaultRes = BaseResponseDTO.getDefaultResDto();
			defaultRes.setErrorMsg(e.getOutMsg());
			defaultRes.setErrorCode(e.getCode());
			resDto.setResData(defaultRes);
			logger.error("CommonAbstractHander XFUNCheckedException error: ", e);
		} catch (Exception e) {
			logger.error("CommonAbstractHander error: ", e);
			resDto = new BaseResponseDTO<DefaultRes>();
			DefaultRes defaultRes = BaseResponseDTO.getDefaultResDto();
			resDto.setResData(defaultRes);
		} finally {
			// 记录日志
			logger.debug("API业务处理结束:=>" + JSON.toJSON(resDto));
		}
		// 返回结果
		return resDto;
	}

	public abstract BaseResponseDTO doBusiness(BaseRequestDTO reqDto);
}
